import axios from "axios";
import { showToast } from "vant";
// import { getToken } from "@/utils/permission";
// import { removeToken } from "@/utils/permission";
import router from "@/router/index";
const errorHandler = (status, info) => {
  switch (status) {
    case 400:
      console.log("400 - 语义错误");
      break;
    case 401:
      console.log("401 - 服务器认证失败");
      break;
    case 403:
      console.log("403 - 服务器拒绝访问");
      break;
    case 404:
      console.log("404 - 地址错误");
      break;
    case 500:
      console.log("500 - 服务器遇到意外");
      break;
    case 502:
      console.log("502 - 服务器无响应");
      break;
    default:
      console.log(info);
      break;
  }
};

// 创建axios实例
const instance = axios.create({
  // 放置网络请求的公共参数
  timeout: 5000, // 5s后超时
});

// 拦截器最常用
// 1、发送请求之前
instance.interceptors.request.use(
  (config) => {
    config.headers["Authorization"] = "Bearer " + getToken();
    // config.headers["studentId"] = localStorage.getItem('isDefaultStudent');
    config.headers["Content-Type"] = "application/json;charset=UTF-8";
    // config中存在网络请求的所有信息
    if (config.method === 'get' && config.params) {
      let url = config.url + '?';
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName];
        var part = encodeURIComponent(propName) + "=";
        if (value !== null && typeof(value) !== "undefined") {
          if (typeof value === 'object') {
            for (const key of Object.keys(value)) {
              let params = propName + '[' + key + ']';
              var subPart = encodeURIComponent(params) + "=";
              url += subPart + encodeURIComponent(value[key]) + "&";
            }
          } else {
            url += part + encodeURIComponent(value) + "&";
          }
        }
      }
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 2、接收响应后
instance.interceptors.response.use(
  (response) => {
    // 三目运算根据状态码来判断接收数据还是拒绝数据
    if (response.status === 200) {
      let data = response.data
      if (data.code == 200) {
        //接口响应成功
        return Promise.resolve(response.data);
      } else if (data.code == 401) {
        // removeToken();
        router.replace('/login');
        // return Promise.reject(data.msg);
      } {
        // showToast(data.msg);
        return Promise.reject(data.msg);
      }

      // if (data.code == 401) {
      //   //用户不存在，重新登录
      //   return Promise.resolve(response);
      // }

      
    } else {
      return Promise.reject(response);
    }
  },
  (error) => {
    const { response } = error;
    showToast(response.info);
    errorHandler(response.status, response.info);
  }
);



// 导出
export default instance;

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function Get(url, params) {
  return new Promise((resolve, reject) => {
    instance
      .get(url, {
        params: params,
      })
      .then((res) => {
        console.log('请求结果为:',res.data)
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function Post(url, params) {
  return new Promise((resolve, reject) => {
    instance
      .post(url, params)
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}





